#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import re
import shutil
import tkinter as tk
from tkinter import ttk, messagebox, scrolledtext


def md_table_to_html(md_table_lines):
    headers = [h.strip() for h in md_table_lines[0].strip('|').split('|')]
    rows = []
    for line in md_table_lines[2:]:
        if line.strip() == '':
            continue
        cells = [c.strip() for c in line.strip('|').split('|')]
        rows.append(cells)

    html = '<div align="center">\n'
    html += ('<table border="1" cellspacing="0" cellpadding="5" '
             'style="border-collapse: collapse;">\n')
    html += '  <tr>' + ''.join(f'<th style="text-align:center;">{h}</th>' for h in headers) + '</tr>\n'
    for row in rows:
        html += '  <tr>' + ''.join(f'<td style="text-align:center;">{c}</td>' for c in row) + '</tr>\n'
    html += '</table>\n'
    html += '</div>'
    return html


def convert_content(content):
    lines = content.splitlines()
    in_code_block = False
    out_lines = []

    img_line_pattern = re.compile(r'^\s*!\[([^\]]*?)\]\((.+?)\)\s*$')
    html_img_start_pattern = re.compile(r'^\s*<p\s+align=["\']center["\']\s*>', re.IGNORECASE)
    html_img_end_pattern = re.compile(r'^\s*</p>', re.IGNORECASE)
    table_start_pattern = re.compile(r'^\s*<table\b', re.IGNORECASE)
    table_end_pattern = re.compile(r'^\s*</table>', re.IGNORECASE)
    md_table_sep_pattern = re.compile(r'^\s*\|?(\s*[:-]+[-| :]*)\|?\s*$')

    def ensure_blank_line_before():
        if len(out_lines) == 0 or out_lines[-1].strip() != '':
            out_lines.append('')

    def ensure_blank_line_after():
        if len(out_lines) == 0 or out_lines[-1].strip() != '':
            out_lines.append('')

    i = 0
    while i < len(lines):
        line = lines[i]

        if line.strip().startswith("```"):
            in_code_block = not in_code_block
            out_lines.append(line)
            i += 1
            continue

        if in_code_block:
            out_lines.append(line)
            i += 1
            continue

        # 图片处理部分保持不变
        m = img_line_pattern.match(line)
        if m:
            alt = m.group(1).strip().replace('"', '&quot;')
            path = m.group(2).strip()
            if path.startswith('<') and path.endswith('>'):
                path = path[1:-1].strip()
            print(f"[DEBUG] 处理图片: alt='{alt}', path='{path}'")
            if not os.path.isfile(path):
                print(f"[WARNING] 图片文件不存在: {path}")

            ensure_blank_line_before()
            out_lines.append('<div align="center">')
            out_lines.append(f'  <img src="{path}" alt="{alt}" style="max-width: 100%;">')
            out_lines.append('</div>')
            ensure_blank_line_after()
            i += 1
            continue

        if html_img_start_pattern.match(line):
            ensure_blank_line_before()
            out_lines.append(line)
            i += 1
            while i < len(lines):
                out_lines.append(lines[i])
                if html_img_end_pattern.match(lines[i]):
                    i += 1
                    break
                i += 1
            ensure_blank_line_after()
            continue

        # HTML表格加居中样式，保持原有替换逻辑不变
        if table_start_pattern.match(line):
            table_lines = [line]
            i += 1
            while i < len(lines):
                table_lines.append(lines[i])
                if table_end_pattern.match(lines[i]):
                    break
                i += 1
            ensure_blank_line_before()
            modified_table_lines = []
            for l in table_lines:
                if re.match(r'^\s*<table\b', l, re.IGNORECASE):
                    l = re.sub(r'<table\b[^>]*>',
                               '<table style="margin: 0 auto; border: 1px solid #000; border-collapse: collapse;" cellpadding="5" cellspacing="0">',
                               l, flags=re.IGNORECASE)
                modified_table_lines.append(l)
            out_lines.extend(modified_table_lines)
            ensure_blank_line_after()
            i += 1
            continue

        # Markdown表格转html
        if '|' in line:
            if i + 1 < len(lines) and md_table_sep_pattern.match(lines[i + 1]):
                table_block = [line, lines[i + 1]]
                i += 2
                while i < len(lines) and ('|' in lines[i] and lines[i].strip() != ''):
                    table_block.append(lines[i])
                    i += 1
                html_table = md_table_to_html(table_block)
                ensure_blank_line_before()
                out_lines.append(html_table)
                ensure_blank_line_after()
                continue
            else:
                out_lines.append(line)
                i += 1
                continue

        out_lines.append(line)
        i += 1

    # 清理多余空行
    final_lines = []
    blank_flag = False
    for l in out_lines:
        if l.strip() == '':
            if not blank_flag:
                final_lines.append('')
            blank_flag = True
        else:
            final_lines.append(l)
            blank_flag = False

    return '\n'.join(final_lines).rstrip() + '\n'


def list_md_files():
    return [f for f in os.listdir('.') if f.lower().endswith('.md') and os.path.isfile(f)]


def load_file(filename):
    with open(filename, 'r', encoding='utf-8') as f:
        return f.read()


def save_with_backup(filename, content):
    bak_file = filename + '.bak'
    shutil.copy2(filename, bak_file)
    with open(filename, 'w', encoding='utf-8') as f:
        f.write(content)
    return bak_file


def on_file_select(event):
    selection = file_listbox.curselection()
    if not selection:
        return
    selected = file_listbox.get(selection[0])
    content = load_file(selected)
    preview_text.delete(1.0, tk.END)
    preview_text.insert(tk.END, content)


def on_convert():
    selection = file_listbox.curselection()
    if not selection:
        messagebox.showwarning("提示", "请先选择一个文件")
        return
    selected = file_listbox.get(selection[0])
    original_content = load_file(selected)
    converted_content = convert_content(original_content)

    if original_content == converted_content:
        messagebox.showinfo("提示", "没有需要转换的内容")
        return

    bak_file = save_with_backup(selected, converted_content)
    messagebox.showinfo("完成", f"文件已转换并覆盖：{selected}\n备份文件：{bak_file}")

    preview_text.delete(1.0, tk.END)
    preview_text.insert(tk.END, converted_content)


root = tk.Tk()
root.title("Markdown 图片与表格居中转换工具")
root.geometry("900x600")

frame_left = ttk.Frame(root)
frame_left.pack(side=tk.LEFT, fill=tk.Y, padx=5, pady=5)

ttk.Label(frame_left, text="当前目录下的 Markdown 文件").pack(anchor="w")
file_listbox = tk.Listbox(frame_left, width=40, height=30)
file_listbox.pack(fill=tk.Y, expand=True)

for md_file in list_md_files():
    file_listbox.insert(tk.END, md_file)

file_listbox.bind("<<ListboxSelect>>", on_file_select)

frame_right = ttk.Frame(root)
frame_right.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True, padx=5, pady=5)

ttk.Label(frame_right, text="文件内容预览").pack(anchor="w")
preview_text = scrolledtext.ScrolledText(frame_right, wrap=tk.WORD)
preview_text.pack(fill=tk.BOTH, expand=True)

btn_convert = ttk.Button(frame_right, text="转换并覆盖", command=on_convert)
btn_convert.pack(pady=5)

root.mainloop()
